/*
 * @Author: LF
 * @Description: 注册页
 * @Date: 2020-10-21 08:38:38
 * @LastEditTime: 2020-10-23 09:34:30
 */
import React, { Component } from 'react'
// 引入信息提示框
import { message, Form, Input, Button } from 'antd'
import { userRegister } from '@/services/user'

class register extends Component {
  // 注册
  register = (e) => {
    e.preventDefault()
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        // 校验通过则发送注册请求
        let { data: res } = await userRegister(values)
        if (res && res.ok !== 1) {
          // 否则提示用户注册失败
          return message.error('注册失败！')
        }
        // 提示用户注册成功
        message.success(res.msg)
        // 1秒后跳转到登录页
        setTimeout(() => {
          window.location.href = '/login'
        }, 1000)
      }
    })
  }

  comfirmPasswordCheck = (rule, value, callback) => {
    if (!value) {
      callback('确认密码不能为空!')
    } else if (
      value !== this.props.form.getFieldsValue(['password']).password
    ) {
      callback('两次输入的密码不一致!')
    }
    callback()
  }

  render() {
    const { getFieldDecorator } = this.props.form
    return (
      <div className="center-nav">
        <div className="center-nav-left">
          <div className="user-handle-box">
            <h1>注册</h1>
            <hr />
            <Form onSubmit={this.register}>
              <Form.Item>
                {getFieldDecorator('username', {
                  rules: [
                    {
                      required: true,
                      message: '账号不能为空!'
                    }
                  ]
                })(<Input placeholder="请输入账号" />)}
              </Form.Item>
              <Form.Item>
                {getFieldDecorator('password', {
                  rules: [
                    {
                      required: true,
                      message: '密码不能为空!'
                    },
                    {
                      min: 6,
                      max: 18,
                      message: '密码必须在6-18位之间!'
                    }
                  ]
                })(<Input.Password placeholder="请输入密码" />)}
              </Form.Item>
              <Form.Item>
                {getFieldDecorator('comfirmPassword', {
                  rules: [
                    {
                      validator: this.comfirmPasswordCheck
                    }
                  ]
                })(<Input.Password placeholder="请再次输入密码" />)}
              </Form.Item>
              <Form.Item>
                <Button htmlType="submit">注册</Button>
              </Form.Item>
            </Form>
          </div>
        </div>
        <div className="center-nav-right"></div>
      </div>
    )
  }
}

const registerForm = Form.create()(register)
export default registerForm
